<template>
  <div class="pre-book">
    <div class="scheduleTable">
      <div class="scheduleTableTitle">
        <el-form ref="ruleForm" label-width="60px" @submit.native.prevent>
          <el-row :gutter="10">
            <el-col :span="3">
              <el-form-item label="店铺" prop="shop">
                <el-select v-model="shop" placeholder="请选择" style="width:100%" size="mini" @change="changeShop">
                  <el-option v-for="item in shopArr" :key="item.id" :label="item.storeName" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="17">
              <div class="changeDate">
                <i class="el-icon-arrow-left eicon" @click="preDate"></i>
                <div class="week-date">
                  <p>{{ dateRange }}</p>
                  <p class="back-today" @click="curDate">返回今天</p>
                </div>
                <i class="el-icon-arrow-right eicon" @click="nextDate"></i>
              </div>
            </el-col>
            <el-col :span="4">
              <el-button size="mini" @click="handleHistory" v-hasPermission="permission.history">预约历史</el-button>
              <el-button size="mini" @click="handleAdd">预约</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div class="scheduleContent">
        <div class="weekList">
          <span v-for="(item, index) in weekList" :key="index" :class="{ 'active': activeIndex == index }"
            @click="changeIndex(index)">{{ formatDate(item) }}</span>
        </div>
        <div class="day-time">
          <div class="total-num">{{ completeTotalData }}/{{ totalData }}</div>
          <div class="step-wrap" id="stepWrap">
            <div class="dateStep">
              <span class="dateStepTxt" v-for="(item, index) in dateTime" :key="index">{{ item }}</span>
            </div>
          </div>
        </div>
        <div class="addScrollHeight" v-loading="tableLoading">
          <div class="numListBoxCont clearfix" id="numListBoxCont">
            <div class="numListBox">
              <div class="seatNums" v-for="(item, index) in coachArr" :key="index">
                <span>{{ item.userName }}</span>
                <p style="margin-top: 5px;">{{ item.completeCount }}/{{ item.dateData.length }}</p>
                <!-- <div class="trainer-reverse" @click="handleAdd">预约</div> -->
              </div>
            </div>
          </div>
          <div class="teables" id="teables">
            <ul class="listUl">
              <li class="clearfix" v-for="(item, index) in coachArr" :key="index">
                <div class="contents clearfix">
                  <div class="normalStatusBox" v-for="(o, i) in 24" :key="i">
                    <div class="table-item" v-if="setIndexAndStyle(i, item.dateData)">
                      <div v-for="(dataItem, d) in item.dateData" :key="d">
                        <div class="toBeClassBox" @click="handleEdit(dataItem.item)" :style="getItemStyle(dataItem)"
                          v-if="i === parseInt(dataItem.classStartTime.split(':')[0])"
                          :class="{ 'finish': dataItem.appointmentStatus === 1 || dataItem.appointmentStatus === -1 }">
                          <span class="timeBox">{{ dataItem.classTime }}</span>
                          <span class="course">{{ dataItem.courseName }}</span>
                          <span class="coachName">{{ dataItem.item.memberUserName }}</span>
                          <i class="icon-finish" v-if="dataItem.appointmentStatus === 1">完成</i>
                          <i class="icon-finish" v-if="dataItem.appointmentStatus === -1">已作废</i>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>

    <!-- 编辑弹窗 -->
    <prebook-edit @closeDialog="closeDialog('edit')" @confirmDialog="confirmDialog('edit')"
      @handleClose="closeDialog('edit')" v-if="dialogPrebookEdit" :dialogVisible="dialogPrebookEdit">
    </prebook-edit>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import cvueTable from '@/components/cvue-table'
import prebookEdit from './prebookEdit'
import dayjs from 'dayjs'
export default {
  name: 'index1',
  components: {
    cvueTable,
    prebookEdit
  },
  data() {
    return {
      tableLoading: false,
      dialogPrebookEdit: false,
      searchArr: [
        { label: 'ID', value: 'user_id' },
        { label: '账号', value: 'username' },
        { label: '用户名', value: 'nick_name' },
        { label: '手机号', value: 'phone' }
      ],
      actionType: 'add',
      rowData: {},
      shop: '',
      shopArr: [],
      dateTime: [
        '00:00',
        '01:00',
        '02:00',
        '03:00',
        '04:00',
        '05:00',
        '06:00',
        '07:00',
        '08:00',
        '09:00',
        '10:00',
        '11:00',
        '12:00',
        '13:00',
        '14:00',
        '15:00',
        '16:00',
        '17:00',
        '18:00',
        '19:00',
        '20:00',
        '21:00',
        '22:00',
        '23:00',
        '23:30'
      ],
      coachArr: [],
      weekList: [],
      dateRange: '',
      datePage: 0,
      activeIndex: 0,
      itemStyle: { 'left': '73px' },
      ccourseArr: [],
      completeTotalData: 0,
      totalData: 0
    }
  },
  computed: {
    ...mapGetters(['token', 'role'])
  },
  mounted() {
    var teables = document.getElementById('teables')
    var numListBoxCont = document.getElementById('numListBoxCont')
    var stepWrap = document.getElementById('stepWrap')
    teables.onscroll = function (event) {
      numListBoxCont.scrollTop = teables.scrollTop
      stepWrap.scrollLeft = teables.scrollLeft
    }
    teables.scrollLeft = 1300
    this.setWeekList(this.datePage)
    this.getShops()
  },
  methods: {
    changeShop(val) {
      this.getCoachList(val)
    },
    // 获取店铺
    getShops() {
      this.$store.dispatch('manage/StoreListMy', '').then(res => {
        // console.log(res)
        if (res.code == '200') {
          var data = res.data
          this.shopArr = data
          // console.log(this.role[0])
          if (this.role[0] == 'ADMIN') {
            this.shopArr = [{ storeName: '全部', id: '' }].concat(this.shopArr)
          }
          // console.log(this.shopArr)
          this.shop = this.shopArr[0].id
          this.getCoachList(this.shop)
        }
      })
    },
    // 获取教练
    getCoachList(storeId) {
      var params = {
        storeId: storeId
      }
      this.$store.dispatch('manage/CoachVisibleList', params).then(res => {
        // console.log(res)
        if (res.code == '200') {
          var data = res.data
          // this.coachArr = data

          var monDay = this.weekList[this.activeIndex].format('YYYY-MM-DD')
          var start = monDay + ' 00:00:00'
          var end = monDay +  ' 23:59:59'
          this.getPreOrderList(storeId, start, end, data)
        }
      }).catch(err => {
        console.log(err)
      })
    },
    getPreOrderList(storeId, start, end, coachArr) {
      var params = {
        current: 1,
        size: 1000,
        end: end,
        ext: {},
        key: '',
        orders: [
          {
            order: 'desc',
            sort: 'createTime'
          }
        ],
        // signCourseId: 0,
        start: start,
        storeId: storeId
      }
      this.$store.dispatch('manage/AppointmentPage', params).then(res => {
        // console.log(res)
        if (res.code == '200') {
          var data = res.data.records
          // console.log(data)
          coachArr.forEach((item, index) => {
            item.dateData = []
          })
          this.completeTotalData = 0
          this.totalData = 0
          for (var i = 0; i < coachArr.length; i++) {
            coachArr[i].completeCount = 0
            for (var j = 0; j < data.length; j++) {
              if (coachArr[i].id === data[j].coachUserId && data[j].appointmentStatus != 2 && data[j].appointmentStatus != 3) {
                if (data[j].appointmentStatus === 1) {
                  coachArr[i].completeCount++
                  this.completeTotalData++
                }
                coachArr[i].dateData.push({
                  startTime: data[j].classStartTime,
                  endTime: data[j].classEndTime,
                  classStartTime: data[j].classStartTime.split(' ')[1],
                  classEndTime: data[j].classEndTime.split(' ')[1],
                  classTime: data[j].classStartTime.split(' ')[1] + '-' + data[j].classEndTime.split(' ')[1],
                  courseName: data[j].courseSnapshotName,
                  coachName: data[j].coachUserName,
                  appointmentStatus: data[j].appointmentStatus,
                  item: data[j]
                })
                this.totalData++
              }
            }
          }
          this.coachArr = coachArr
          // console.log(this.coachArr)
        }
      })
    },
    setIndexAndStyle(i, dateData) {
      var dateIndexArr = []
      dateData.forEach((item, index) => {
        dateIndexArr.push(parseInt(item.classStartTime.split(':')[0]))
      })
      return dateIndexArr.indexOf(i) >= 0
    },
    getItemStyle(dataItem) {
      // console.log(dataItem)
      var start = (new Date(dataItem.startTime)).getTime()
      var end = (new Date(dataItem.endTime)).getTime()
      var minusTime = ((end - start) / (1000 * 60 * 60)).toFixed(1)
      if (parseInt(dataItem.classStartTime.split(':')[1]) > 0) {
        return { 'left': '73px', 'width': 142 * minusTime + 'px' }
      } else {
        return { 'width': 142 * minusTime + 'px' }
      }
    },
    handleHistory() {
      this.$router.push('/home/prebook-history')
    },
    changeIndex(index) {
      this.activeIndex = index
      this.getCoachList(this.shop)
    },
    preDate() {
      this.datePage--
      this.setWeekList(this.datePage)
      this.changeIndex(0)
    },
    nextDate() {
      this.datePage++
      this.setWeekList(this.datePage)
      this.changeIndex(0)
    },
    curDate() {
      this.datePage = 0
      this.setWeekList(this.datePage)
      this.changeIndex(0)
    },
    setWeekList(page) {
      var index = 0
      for (let i = page * 7; i <= 6 + page * 7; i++) {
        this.$set(this.weekList, index, dayjs().add(i, 'day'))
        index++
      }
      this.dateRange = dayjs().add(page * 7, 'day').format('YYYY-MM-DD') + '-' + dayjs().add(6 + page * 7, 'day').format('YYYY-MM-DD')
    },

    formatDate(item) {

      var week = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
      let d = ''

      if (item.format('YYYY-MM-DD') == dayjs().format('YYYY-MM-DD')) {
        d = '今天'
      }
      if (item.format('YYYY-MM-DD') == dayjs().add(1, 'day').format('YYYY-MM-DD')) {
        d = '明天'
      }
      if(!d){
        d = week[item.format('d')]
      }



      return d + ' ' + item.format('MM/DD')
    },
    getWeekDay(date) {
      var week = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
      var latest = new Date(date)
      return week[latest.getDay()]
    },
    // 新增
    handleAdd() {
      this.actionType = 'add'
      this.dialogPrebookEdit = true
    },
    // 编辑
    handleEdit(row) {
      this.actionType = 'edit'
      this.dialogPrebookEdit = true
      this.rowData = row
    },
    handleDelete(row) {
      this.$confirm('确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var params = {
          id: row.id
        }
        this.$store.dispatch('manage/UserDelete', params).then(res => {
          this.$message({
            type: 'success',
            message: res.msg
          })
          this.tablePage = 1
          this.handleList(this.selectId, this.selectUsername, this.selectNickname)
        }).catch((err) => {
          this.$message({ type: 'error', message: err.msg })
        })
      }).catch(() => {
      })
    },
    // 关闭弹窗
    closeDialog(params) {
      if (params == 'edit') {
        this.dialogPrebookEdit = false
        this.getCoachList(this.shop)
      }
    },
    // 确认
    confirmDialog(params) {
      if (params == 'edit') {
        this.dialogPrebookEdit = false
        this.getCoachList(this.shop)
      }
    }
  }
}
</script>

<style lang="scss">
.pre-book {
  padding: 0px !important;
  height: 100%;
  background: #fff;
  overflow: hidden;

  .icon-finish {
    width: 30px;
    height: 30px;
    display: inline-block;
    border-radius: 50%;
    position: absolute;
    right: 5px;
    bottom: 5px;
    line-height: 30px;
    text-align: center;
    font-size: 10px;
    border: 1px solid #ccc;
    background: #ccc;
    transform: rotate(-30deg);
  }

  .finish {
    border-left: 3px solid #ccc !important;
    background: #eee !important;
  }

  .scheduleTable {
    height: 100%;
  }

  .scheduleTableTitle {
    height: 63px;
    padding-top: 15px;
    border-bottom: 1px solid #f5f5f5;
    box-sizing: border-box;

    .el-form-item {
      margin-bottom: 10px !important;
    }

    .changeDate {
      display: flex;
      justify-content: center;
      align-items: center;

      .eicon {
        font-size: 18px;
        font-weight: bold;
        cursor: pointer;
      }

      .week-date {
        margin: 0 30px;
        text-align: center;
        font-size: 15px;
        font-weight: bold;

        .back-today {
          cursor: pointer;
          font-size: 13px;
          font-weight: normal;
          color: #1890ff;
          margin-top: 3px;
        }
      }
    }
  }

  .scheduleContent {
    overflow: hidden;
    height: calc(100% - 63px);
    padding: 0 20px;
    box-sizing: border-box;

    .weekList {
      display: flex;
      height: 50px;
      justify-content: space-between;
      align-items: center;
      padding: 0 10px;
      cursor: pointer;

      .active {
        color: #1890ff;
      }
    }

    .day-time {
      overflow: hidden;
      border: 1px solid #EBEEF5;
      background: #FAFAFA;
      position: relative;
      padding-left: 84px;

      .total-num {
        width: 84px;
        height: 40px;
        line-height: 40px;
        text-align: center;
        position: absolute;
        left: 0;
        top: 0;
        z-index: 100;
        background: #FAFAFA;
        font-size: 14px;
        font-weight: 500;
        color: #383838;
      }

      .step-wrap {
        width: 100%;
        overflow: hidden;
      }

      .dateStep {
        position: relative;
        min-width: 3582px;
        height: 40px;
        background: #fafafa;

        .dateStepTxt {
          width: 143px;
          font-size: 14px;
          font-weight: 500;
          float: left;
          line-height: 40px;
          text-indent: 32px;
          font-family: HelveticaNeue;
          color: #495161;
        }
      }
    }

    .addScrollHeight {
      display: flex;
      border-right: 1px solid rgb(235, 238, 245);
      height: calc(100% - 107px);

      .numListBoxCont {
        position: relative;
        overflow: hidden;
        height: calc(100% - 10px);
        padding-bottom: 20px;
        box-sizing: border-box;

        .numListBox {
          float: left;
          position: relative;

          .seatNums {
            width: 90px;
            height: 74px;
            background: #fafafa;
            z-index: 100;
            position: relative;
            border-right: 1px solid #ebeef5;
            border-left: 1px solid #ebeef5;
            border-bottom: 1px solid #ebeef5;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;

            .trainer-reverse {
              display: inline-block;
              width: 40px;
              height: 19px;
              background: #169bd5;
              border-radius: 4px;
              text-align: center;
              line-height: 20px;
              font-size: 12px;
              color: #FFFFFF;
              margin-top: 5px;
              cursor: pointer;
            }
          }
        }
      }

      .teables {
        width: 100%;
        height: 100%;
        position: relative;
        overflow: scroll;
        padding-bottom: 20px;
        box-sizing: border-box;

        .listUl {
          margin-left: 46px;
          border-left: 1px solid rgb(235, 238, 245);
          min-width: 3480px;

          li {
            border-left: 0 !important;

            .contents {
              position: relative;
            }

            .normalStatusBox {
              width: 142px;
              height: 74px;
              display: inline-block;
              border-right: 1px solid #ebeef5;
              border-bottom: 1px solid #ebeef5;
              text-align: center;
              float: left;
              position: relative;

              .table-item {
                height: 74px;
                position: absolute;

                .toBeClassBox {
                  border-left: 3px solid rgb(83, 210, 194);
                  background: rgb(221, 246, 243);
                  width: 142px;
                  height: 74px;
                  position: relative;
                  z-index: 2000;
                  cursor: pointer;

                  .timeBox {
                    position: absolute;
                    left: 8px;
                    top: 5px;
                    color: #383838;
                    font-size: 12px;
                    font-weight: 500;
                    line-height: 17px;
                    white-space: nowrap;
                  }

                  .course {
                    position: absolute;
                    left: 8px;
                    top: 23px;
                    color: #383838;
                    font-size: 14px;
                    width: 120px;
                    text-align: left;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                    font-weight: 500;
                    line-height: 20px;
                  }

                  .coachName {
                    position: absolute;
                    left: 0;
                    top: 50px;
                    color: #818c95;
                    width: 126px;
                    padding-left: 8px;
                    text-align: left;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                    font-size: 12px;
                    color: rgba(56, 56, 56, 0.6);
                    line-height: 17px;
                  }
                }
              }
            }
          }
        }

        .clearfix::before,
        .clearfix::after {
          content: '';
          display: table;
        }

        .clearfix:after {
          clear: both;
        }
      }
    }
  }
}
</style>
